#include <stdio.h>

//#include <linux/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#define UDP_PORT 3000

int main(int argc,char *argv[])
{
    int sfd,ret;
    struct sockaddr_in sAddr,cAddr;
    sfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sfd == -1)
    {
        printf("error:%s\n",strerror(errno));
        return sfd;
    }
    sAddr.sin_family = AF_INET;
    sAddr.sin_addr.s_addr = INADDR_ANY;
    sAddr.sin_port = htons(UDP_PORT);
    ret = bind(sfd,(sockaddr*)(&sAddr),sizeof(sAddr));
    if(-1 == ret)
    {
        printf("error:%s\n",strerror(errno));
        return ret;
    }
    char buf[10000] = {0};
    while(1)
    {
        socklen_t len = sizeof(sockaddr);
        ssize_t s = recvfrom(sfd, buf, sizeof(buf), 0, (sockaddr*)(&cAddr), &len);
        if(-1 == s)
        {
            printf("error:%s\n",strerror(errno));
            return ret;
        }
        if(0 != s)
        {
            ret = write(STDOUT_FILENO,buf,s);
            if(-1 == ret)
            {
                printf("error:%s\n",strerror(errno));
                return ret;
            }


        FILE* fp = fopen("textfile.txt", "wb+");  
    	if(NULL == fp)
    	{
    		printf("open file fail!\n");
    		return;
    	}
    	fwrite(buf, 1, s, fp);
    	//printf("open file success\n");
    	fclose(fp);

           //printf(" buf = %s \n", buf);
        }
    }
}
